package org.jeecg.modules.api.util;


import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

import static org.jeecg.modules.api.util.Constants.TSP_PASSWORD;
import static org.jeecg.modules.api.util.Constants.TSP_USERNAME;

/**
 * @author: Dean
 * @since: 2019/9/28
 */
@Component
public class HttpClient {
    private  CloseableHttpClient getHttpClient(){
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(TSP_USERNAME, TSP_PASSWORD);
        provider.setCredentials(AuthScope.ANY, credentials);
        return  HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    }

    /*
     *  url： 请求的url
     *  requestDTO： post请求的url
     *  此处根据自己需求更改为post请求还是其他请求
     */
    public String createStream(String url, Object o) {
        CloseableHttpClient httpClient = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        String s = "";
        String s1 = FastJsonUtils.convertObjectToJSON(o);
        httpPost.setEntity(new StringEntity(s1, Charset.forName("UTF-8")));
        try {

            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            s = EntityUtils.toString(entity);
            httpClient.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }
}
